package com.wolf.server;

import com.wolf.core.Header;
import com.wolf.core.Protocol;
import com.wolf.core.RequestEntity;
import com.wolf.core.ResponseEntity;
import com.wolf.enums.Command;
import com.wolf.serialization.SerialFactory;
import com.wolf.serialization.Serializer;
import com.wolf.spring.WolfContextUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.lang.reflect.Method;

/**
 * @auth: dylan
 * @Desc: 入栈处理器
 * @Time: 2024/5/1
 */
@Slf4j
public class ServerInboundHandler extends SimpleChannelInboundHandler<Protocol<RequestEntity>> {
    @Override
    protected void channelRead0(ChannelHandlerContext context, Protocol<RequestEntity> protocol) throws Exception {
        log.info("接收到消息信息。。。。。。。");
        //获取对象
        BeanDispatcher dispatcher = BeanDispatcher.getInstance();
        Object result = dispatcher.process(protocol.getContent());
        //把获取的结果写回到客户端
        Header header = protocol.getHeader();
        header.setCommand(Command.RESPONSE.getCode());
        ResponseEntity response=new ResponseEntity();
        response.setCode(200);
        response.setData(result);
        response.setMessage("success");

        Serializer serializer = SerialFactory.get(header.getSerialType());
        byte[] bytes = serializer.serializer(response);
        header.setDataLength(bytes.length);
        Protocol<ResponseEntity> respProtocol=new Protocol<>();
        respProtocol.setHeader(header);
        respProtocol.setContent(response);
        context.channel().writeAndFlush(respProtocol);
    }
}
